package cn.org.intelli.zffserver.service;


import cn.org.intelli.zffserver.entity.DataBaseEntity;
import cn.org.intelli.zffserver.entity.DeletedJobEntity;
import cn.org.intelli.zffserver.entity.ModelEntity;
import cn.org.intelli.zffserver.repository.DataBaseRepository;
import cn.org.intelli.zffserver.repository.DeletedJobRepository;
import cn.org.intelli.zffserver.repository.ModelRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DeleteJobService {
    /*  27 */   private static final Logger log = LoggerFactory.getLogger(cn.org.intelli.zffserver.service.DeleteJobService.class);


    @Autowired
    private DeletedJobRepository deletedJobRepository;


    @Autowired
    private ModelRepository modelRepository;

    @Autowired
    private DataBaseRepository dataBaseRepository;


    @Scheduled(cron = "0 0 0 1 * ?")
    @Transactional
    public void clearJobResult() throws Exception {
        /*  44 */
        log.info("@ClearJobResult: start to clear deleted job result");

        /*  46 */
        List<DeletedJobEntity> deleteJobs = this.deletedJobRepository.findAllByDeleteTimeLessThanEqual(new Date());

        /*  48 */
        Map<String, List<String>> modelJobCache = new HashMap<>();
        /*  49 */
        for (DeletedJobEntity deleteJob : deleteJobs) {
            /*  50 */
            String modelId = deleteJob.getModelId();
            /*  51 */
            String jobId = deleteJob.getJobId();
            /*  52 */
            if (modelJobCache.get(modelId) == null) {
                /*  53 */
                List<String> tmp = new ArrayList<>();
                /*  54 */
                tmp.add(jobId);
                /*  55 */
                modelJobCache.put(modelId, tmp);
                continue;
            }
            /*  57 */
            modelJobCache.get(modelId).add(jobId);
        }


        /*  61 */
        List<String> errorJobIds = new ArrayList<>();
        /*  62 */
        for (Map.Entry<String, List<String>> entry : modelJobCache.entrySet()) {
            /*  63 */
            String modelId = entry.getKey();
            /*  64 */
            List<String> list = modelJobCache.get(modelId);
            try {
                /*  66 */
                deleteJobResultsInDb(modelId, list);
                /*  67 */
            } catch (Exception e) {
                /*  68 */
                log.error("@ClearJobResult: job results in modelId {} delete error! error is {}", modelId, e
/*  69 */.getMessage());
                /*  70 */
                errorJobIds.addAll(list);
            }
        }


        /*  75 */
        deleteJobs.removeAll(errorJobIds);


        /*  78 */
        List<String> jobIds = deleteJobs.stream().map(deleteJob -> deleteJob.getJobId()).collect(Collectors.toList());
        /*  79 */
        this.deletedJobRepository.deleteAllByJobIdIn(jobIds);
        /*  80 */
        log.info("@ClearJobResult: deleted job result cleared");
    }

    private void deleteJobResultsInDb(String modelId, List<String> jobIds) throws Exception {
        /*  84 */
        ModelEntity model = this.modelRepository.findById(modelId).get();
        /*  85 */
        String dbId = model.getDestinationDbId();
        /*  86 */
        String tableName = model.getModelCode() + "_RESULT";

        /*  88 */
        DataBaseEntity database = this.dataBaseRepository.findById(dbId).get();
        /*  89 */
        String dbType = database.getDbType();
        /*  90 */
        switch (dbType) {
            case "dm":
                /*  92 */
                deleteJobResultInDm(jobIds, database, tableName);
                break;
            case "clickhouse":
                /*  95 */
                deleteJobResultInClickhouse(jobIds, database, tableName);
                break;
        }
    }


    private void deleteJobResultInDm(List<String> jobIds, DataBaseEntity dataBase, String tableName) throws Exception {
        /* 113 */
        String driverName = dataBase.getDriverName();
        /* 114 */
        String dbUrl = dataBase.getDbUrl();
        /* 115 */
        String dbUserName = dataBase.getDbUserName();
        /* 116 */
        String dbPassword = dataBase.getDbPassword();
        /* 117 */
        String schemaName = dataBase.getSchemaName();

        /* 119 */
        Class.forName(driverName);
        /* 120 */
        Connection conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
        /* 121 */
        Statement smt = conn.createStatement();

        /* 123 */
        String jobIdsStr = jobIds.stream().map(s -> "'" + s + "'").collect(Collectors.joining(","));
        try {
            /* 125 */
            String deleteSql = "DELETE FROM " + schemaName + "." + tableName + " WHERE JOBID IN (" + jobIdsStr + ")";

            /* 127 */
            smt.execute(deleteSql);
            /* 128 */
        } catch (Exception e) {
            /* 129 */
            e.printStackTrace();
            /* 130 */
            throw new Exception(e);
        } finally {
            /* 132 */
            smt.close();
            /* 133 */
            conn.close();
        }
    }


    private void deleteJobResultInClickhouse(List<String> jobIds, DataBaseEntity dataBase, String tableName) throws Exception {
        /* 148 */
        String driverName = dataBase.getDriverName();
        /* 149 */
        String dbUrl = dataBase.getDbUrl();
        /* 150 */
        String dbUserName = dataBase.getDbUserName();
        /* 151 */
        String dbPassword = dataBase.getDbPassword();
        /* 152 */
        String schemaName = dataBase.getSchemaName();

        /* 154 */
        Class.forName(driverName);
        /* 155 */
        Connection conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
        /* 156 */
        Statement smt = conn.createStatement();

        /* 158 */
        String jobIdsStr = jobIds.stream().map(s -> "'" + s + "'").collect(Collectors.joining(","));
        try {
            /* 160 */
            String deleteSql = "ALTER TABLE " + schemaName + "." + tableName + " DELETE WHERE JOBID IN (" + jobIdsStr + ")";


            /* 163 */
            smt.execute(deleteSql);
            /* 164 */
        } catch (Exception e) {
            /* 165 */
            e.printStackTrace();
            /* 166 */
            throw new Exception(e);
        } finally {
            /* 168 */
            smt.close();
            /* 169 */
            conn.close();
        }
    }
}


/* Location:              C:\Users\admin\Desktop\xxm\zjg11\ZjgCaculate-v1.0.jar!\BOOT-INF\classes\cn\org\intelli\zffserver\service\DeleteJobService.class
 * Java compiler version: 8 (52.0)
 * JD-Core Version:       1.1.3
 */